<template>
  <el-drawer class="drawer_warp" title="选择设备" :visible.sync="drawerPvVisible" size="800px"
    :close-on-press-escape="false" :before-close="handleClose">
    <div class="filter-container g-bgc-fill-el-input">
      <div class="filter-left">
        <el-select v-model="listQuery.menufacturerId" placeholder="品牌" clearable @change="comHandleFilterSelectChange"
          style="width: 104px" class="filter-item">
          <el-option v-for="(item, index) in brandOptions" :key="'br' + index" :label="item.menufacturer"
            :value="item.id" />
        </el-select>
        <el-select v-model="listQuery.storage" placeholder="容量" clearable @change="comHandleFilterSelectChange"
          style="width: 104px" class="filter-item">
          <el-option v-for="(item, index) in storageOptions" :key="'st' + index" :label="item.label" :value="item.id" />
        </el-select>
        <!-- 设备没有软件版本 -->
        <!-- <el-select v-model="listQuery.importance" placeholder="软件版本" clearable @change="comHandleFilterSelectChange"
            style="width: 132px" class="filter-item">
            <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />
          </el-select> -->
        <!-- 这一期前端弄不完 -->
        <!-- <el-select v-model="listQuery.p2pAddress" placeholder="所在地区" clearable @change="comHandleFilterSelectChange"
            class="filter-item" style="width: 132px">
            <el-option v-for="item in p2pAddressOptions" :key="item.key"
              :label="item.display_name + '(' + item.key + ')'" :value="item.key" />
          </el-select> -->
        <el-date-picker v-model="listQuery.date" type="daterange" @change="comHandleFilterDateChange"
          format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss" style="width: 208px;" range-separator=""
          start-placeholder="开始时间" end-placeholder="结束时间">
        </el-date-picker>
        <el-select v-model="listQuery.activedState" placeholder="状态" clearable @change="comHandleFilterSelectChange"
          style="width: 104px" class="filter-item">
          <el-option v-for="item in activedStateOptions" :key="item.id" :label="item.label" :value="item.id" />
        </el-select>
        <np-input-search v-model="listQuery.deviceCode" placeholder="搜索序列号" style="width: 240px;"
          @all-search="comHandleFilterAllSearch" />
      </div>
    </div>

    <el-table class="g-el-table" :data="list" v-loading="listLoading" ref="tableRef"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column label="序列号" prop="deviceCode" width="300">
        <template slot-scope="{row}">
          <span>{{ row.deviceCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="品牌" width="150px">
        <template slot-scope="{row}">
          <span>{{ row.deviceBrand }}</span>
        </template>
      </el-table-column>
      <el-table-column label="容量" width="110px">
        <template slot-scope="{row}">
          <span>{{ row.storage | storageFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="软件版本" width="80px">
        <template slot-scope="{row}">
          <span>{{ row.author }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所在地区" width="95">
        <template slot-scope="{row}">
          <span>{{ row.p2pAddress }}</span>
        </template>
      </el-table-column>
      <el-table-column label="激活时间" width="100">
        <template slot-scope="{row}">
          <span>{{ row.createdDate | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template slot-scope="{row}">
          {{ row.activedState | activedStateFilter }}
        </template>
      </el-table-column>
    </el-table>

    <np-pagination v-show="total > 0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize"
      @pagination="getList" />

    <div class="fotter">
      <div></div>
      <div>
        <el-button type="warning" @click="handleBeSureClick" :loading="submitLoading">确定</el-button>
        <el-button type="info" plain class="btn1" @click="handleCancelClick">取消</el-button>
      </div>
    </div>
  </el-drawer>
</template>
<script>
import { fetchList } from '@/api/equipment-management/list'

const activedStateOptions = [
  // "激活状态,U:未激活,A:已激活"
  {
    label: '已激活',
    id: 'A',
  }, {
    label: '未激活',
    id: 'U',
  }
]

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    brandOptions: {
      type: Array,
      default: () => {
        return []
      }
    },
    infoData: {
      type: Array,
      default: () => {
        return []
      }
    },
  },
  filters: {
    activedStateFilter(status) {
      let v = activedStateOptions.find(el => status === el.id)
      if (v) {
        return v.label
      }
      return '未激活'
    },
    storageFilter(val) {
      /**
       * 导入xls表等，没有单位默认就是 TB
       * 默认存储 GB 列表默认显示GB，如果大于 1Tb 单位就是 TB
       */
      try {
        let radix = 1024;
        let v = Number(val) || 0
        if (v >= radix) {
          // TB
          let a = Number(v / radix).toFixed(3)
          return parseFloat(a) + 'TB';
        }
        // GB
        return parseFloat(v) + 'GB';
      } catch (error) { }
      return ''
    }
  },
  data() {
    return {
      list: null,
      total: 0,
      pageSizes: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200],
      // 页面初始化调接口加载 Loading
      listLoading: true,

      // isFirstLoad: true, // 初始化标志位

      multipleOldCurSelection: [],// 当前列表所有条件选中的数据，不管添加还是删除，都做一个缓存
      multipleNewCurSelection: [],// 当前列表所有条件选中的数据，不管添加还是删除，都做一个缓存
      /**
       * @multipleSelection
       * 选中数组,每次选择往后添加，如果删除就删除选中的一些选项
       * 存取的是 infoData里面的初始数据，及每次点击 取消所有选择 按钮之后的数据 的和
       */
      multipleSelection: [],// 选中数组,每次选择往后添加，如果删除就删除选中的一些选项
      // multipleCacheSelection: [],// 选中数组的缓存，存取的是 infoData里面的初始数据，及每次点击 取消所有选择 按钮之后的数据 的和
      // isClearAll: false, // 判断是否点击过 取消所有选择 按钮之后的数据

      // 页面筛选初始参数对象
      listQuery: {
        pageNum: 1,
        pageSize: 10,

        menufacturerId: undefined,

        storage: undefined,
        startStorage: undefined,
        endStorage: undefined,

        importance: undefined,
        p2pAddress: undefined,
        activedState: undefined,
        deviceCode: undefined,

        date: undefined,
        startDate: undefined,
        endDate: undefined,

        importance: undefined,
        title: undefined,
        type: undefined,
      },
      // 容量单位为 TB
      storageOptions: [{
        id: [1, undefined],
        label: '1TB以下',
      }, {
        id: [1, 1],
        label: '1TB',
      }, {
        id: [1, 5],
        label: '1-5TB',
      }, {
        id: [undefined, 5],
        label: '5TB以上',
      }],
      p2pAddressOptions: [],
      activedStateOptions,

      // 以上都是列表参数，以下都是弹窗本身参数
      drawerPvVisible: false,

      submitLoading: false,
    }
  },
  watch: {
    visible: {
      handler(newVal) {
        this.drawerPvVisible = newVal;
        if (newVal) {
          if (!this.infoData) {
            this.editInfo()
            return
          }
        }
        if (!newVal) {
          this.resetFieldsFrom()
        }
      }
    }
  },
  computed: {
  },
  created() {
    this.getList()
  },
  methods: {
    profilePictureSrc(row) {
      try {
        let base_url = process.env.VUE_APP_IMG_BASE_URL,
          url = row.headUrl;
        if (url) {
          return `${base_url}/${url}`
        }
      } catch (error) { }
      return ""
    },
    editInfo() {
      this.multipleSelection = JSON.parse(JSON.stringify(this.infoData))
      // this.getList()
    },
    resetFieldsFrom() {
      // this.isClearAll = false
      this.drawerPvVisible = false
      this.$emit("update:visible", this.drawerPvVisible)
    },
    handleClose(done) {
      this.resetFieldsFrom()
      done()
    },
    handleCancelClick() {
      this.list.filter(el => {
        if (this.multipleSelection.find(v_el => el.id === v_el.id)) {
          this.$refs.tableRef.toggleRowSelection(el, true);
        } else {
          this.$refs.tableRef.toggleRowSelection(el, false);
        }
      })
      this.resetFieldsFrom()
    },
    handleBeSureClick() {
      let receiverName = []
      try {
        receiverName = this.multipleNewCurSelection;
      } catch (error) {
        console.log(error);
      }
      this.$emit("addSelectSuccessChange", receiverName)
      this.resetFieldsFrom()
    },
    handleSelectionChange(val) {
      if (val.length > 1) {
        this.$refs.tableRef.clearSelection();
        this.$refs.tableRef.toggleRowSelection(val.pop());
      }
      this.multipleOldCurSelection = JSON.parse(JSON.stringify(this.multipleNewCurSelection))
      this.multipleNewCurSelection = val
    },
    getList() {
      let params = { ...this.listQuery }
      delete params.date
      let st = params.storage
      if (st) {
        let radix = 1024;
        if (st[0]) {
          params.startStorage = st[0] * radix
        }
        if (st[1]) {
          params.endStorage = st[1] * radix
        }
      }
      delete params.storage

      this.listLoading = true
      fetchList(params).then(res => {
        if (res.code === 200) {
          this.list = res.data.list
          this.total = res.data.total

          this.$nextTick(() => {
            this.list.filter(el => {
              if (this.multipleSelection.find(v_el => el.id === v_el.id)) {
                this.$refs.tableRef.toggleRowSelection(el, true);
              }
            })

            // Just to simulate the time of the request
            this.listLoading = false
          });
        } else {
          this.listLoading = false
        }
      }).catch(() => {
        this.listLoading = false
      })
    },
    comHandleFilterAllSearch(e, type) {
      this.listQuery.pageNum = 1
      this.getList()
    },
    comHandleFilterSelectChange(e) {
      this.listQuery.pageNum = 1
      this.getList()
    },
    comHandleFilterDateChange(e) {
      this.listQuery.pageNum = 1
      this.listQuery.startDate = e ? e[0] : ''
      this.listQuery.endDate = e ? e[1] : ''
      this.getList()
    },
  }
}
</script>
<style lang="scss" scoped>
.title {
  padding-bottom: 32px;
  font-size: 18px;
  font-weight: 500;
  line-height: 24px;
  color: #15181D;
}

.fotter {
  padding-top: 88px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .btn1 {
    margin-right: 12px;
  }
}

.profile_picture_warp {
  display: flex;
  justify-content: center;
  align-items: center;

  @mixin com_img {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    flex-shrink: 0;
  }

  img {
    @include com_img;
  }

  div {
    @include com_img;
    background: #CCCCCC;
  }
}

.container {
  ::v-deep {
    @media (max-width: 1280px) {
      .np-el-d-body {
        padding: 24px 40px 40px 24px;
        min-height: 264px;
      }
    }
  }
}

.drawer_warp {
  &::v-deep {
    &.el-drawer__wrapper {
      pointer-events: none;

      .el-drawer {
        pointer-events: auto;
      }

      .el-drawer__header {
        font-size: 16px;
        font-weight: 500;
        line-height: 20px;
        color: #15181D;

        .el-checkbox {
          pointer-events: none;
          cursor: no-drop;
        }
      }

      .el-drawer__body {
        padding: 0 40px 40px;
        overflow: auto;
      }
    }
  }
}

::v-deep {
  .np-pagination-total {
    max-width: 106px;
  }
}
</style>